package com.stlm2.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;

public class AppListener implements ServletContextListener {

    private static Logger logger = LoggerFactory.getLogger(AppListener.class);

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        String fsucc = context.getInitParameter("force_succ");
        if ("true".equalsIgnoreCase(fsucc)) {
            try {
                initAppConfig(context);

                AppConfig.appConfigInitError = "succ";
                AppConfig.appConfigInitSucc = true;
            } catch (Throwable eee) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                eee.printStackTrace(pw);
                AppConfig.appConfigInitError = "App Root="
                        + AppConfig.getWebAppRoot() + "\r\n" + eee.getMessage()
                        + "\r\n" + sw.toString();
            }
        } else {
            initAppConfig(context);

            AppConfig.appConfigInitSucc = true;

        }
    }

    private void initAppConfig(ServletContext context) {
        String crsFile = context.getInitParameter("class_res_file");

        String cxtRoot = context.getContextPath();
        if (!"/".equals(cxtRoot))
            cxtRoot += "/";
        AppConfig.setContextPath(cxtRoot);

        String realPath = getWebAppRootPath(context, crsFile);
        AppConfig.setWebAppRoot(realPath);

        String appConfFile = context.getInitParameter("app_conf_file");
        if (appConfFile != null && !appConfFile.equals("")) {
            // web.xml 通过强制指定的路径确定app.xml app.conf.xml app.conf文件的位置
            // 在这种情况下,该目录下的 data template等基于app conf base的目录都应该在那里
            String fb = (new File(appConfFile)).getParentFile()
                    .getAbsolutePath();
            AppConfig.setConfigFileBase(fb);
            logger.info("App Config For Portal WebApp, File Base="
                    + AppConfig.getConfigFileBase());
        } else {
            realPath = realPath.replace('\\', '/');

            if (realPath.endsWith("/"))
                realPath += "WEB-INF/";
            else
                realPath += "/WEB-INF/";

            AppConfig.setConfigFileBase(realPath);
            logger.info("App Config For WebApp, File Base="
                    + AppConfig.getConfigFileBase());
        }

        AppConfig.loadConf();
    }

    private static String getWebAppRootPath(ServletContext sc,
                                            String classResFile) {
        String realPath = sc.getRealPath("/");
        if (realPath != null && !realPath.equals("")) {
            return realPath.replace('\\', '/');
        }

        // 使用class定位
        if (classResFile == null || classResFile.equals(""))
            classResFile = "cres.conf";
        URL url = new Object() {
        }.getClass().getResource("/" + classResFile);
        if (url == null)
            throw new RuntimeException("cannot location webapp root!");

        String abspath = new File(url.getFile()).getParentFile()
                .getParentFile().getParentFile().getAbsolutePath();
        return abspath.replace('\\', '/');
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {

    }


}
